#include "maindialog.h"
#include "ui_maindialog.h"

#include <QTcpSocket>

MainDialog::MainDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::MainDialog)
{
    ui->setupUi(this);

    m_sock = new QTcpServer(this);

    connect(m_sock, &QTcpServer::newConnection, this, &MainDialog::acceptConnection);

    m_sock->listen(QHostAddress::Any, 8888);
}

MainDialog::~MainDialog()
{
    delete ui;
}

void MainDialog::acceptConnection()
{
    qDebug() << "有一个新的客户端连接请求到来！";

    QTcpSocket* sockConn = m_sock->nextPendingConnection();

    connect(sockConn, &QTcpSocket::readyRead, this, &MainDialog::recvMsg);
    connect(sockConn, &QTcpSocket::disconnected, this, &MainDialog::connectClosed);

    m_clients.push_back(sockConn);

    ui->labelOnlineCnt->setText(QString("在线人数：%1").arg(m_clients.size()));
}


void MainDialog::on_btnSend_clicked()
{
    // 将聊天消息发送给所有在线客户端
    QString msg = ui->edtMsg->toPlainText();

    for(QTcpSocket* sock : m_clients)
    {
        sock->write(msg.toUtf8());
    }
}

void MainDialog::recvMsg()
{
    // 获取信号发射者的指针
    QTcpSocket* sock = qobject_cast<QTcpSocket*>(sender());

    // 接收当前所有新数据
    QByteArray data = sock->readAll();

    // 显示在聊天记录框中
    ui->edtRecord->appendPlainText(QString::fromUtf8(data) + "\n\n");

    for(QTcpSocket* sock : m_clients)
    {
        sock->write(data);
    }
}

void MainDialog::connectClosed()
{
    // 获取信号发射者的指针
    QTcpSocket* sock = qobject_cast<QTcpSocket*>(sender());

    m_clients.removeOne(sock);  // 从客户端链表中删除当前下线的客户端

    ui->labelOnlineCnt->setText(QString("在线人数：%1").arg(m_clients.size()));

    sock->deleteLater();
}
